# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: leon

import logging
from coin.base.book import BookBuilderBase
from coin.exchange.gopax.kr_rest.product import GopaxProduct


class BookEntry(object):
  def __init__(self, price, qty):
    self.price = float(price)
    self.qty = float(qty)


class BookBuilder(BookBuilderBase):
  ProductType = GopaxProduct

  def __init__(self, native_symbol, book_builder_observer=None):
    super().__init__("Gopax", native_symbol, book_builder_observer=book_builder_observer)

  def snapshot(self, bids: list, asks: list):
    for data in bids:
      price = float(data['price'])
      qty = float(data['volume'])
      self._insert_bid(price, qty, insert_only=True)

    for data in asks:
      price = float(data['price'])
      qty = float(data['volume'])
      self._insert_ask(price, qty, insert_only=True)

  def update(self, bids: list, asks: list):
    for data in bids:
      price = float(data['price'])
      qty = float(data['volume'])
      if qty > 0:
        self._insert_bid(price, qty, insert_only=False)
      else:
        self._delete_bid(price)

    for data in asks:
      price = float(data['price'])
      qty = float(data['volume'])
      if qty > 0:
        self._insert_ask(price, qty, insert_only=False)
      else:
        self._delete_ask(price)

  def _insert_bid(self, price, qty, insert_only=False):
    assert price > 0
    assert qty > 0
    entry = BookEntry(price, qty)
    if insert_only:
      assert price not in self._bid_price_map
    self._bid_price_map[price] = entry

    if self.ask0() is None:
      return
    bid_price = self.bid0().price
    while self.ask0() is not None and bid_price >= self.ask0().price:
      ask_price = self.ask0().price
      self._delete_ask(ask_price)
      logging.debug('REMOVE CX ASK')

  def _insert_ask(self, price, qty, insert_only=False):
    assert price > 0
    assert qty > 0
    entry = BookEntry(price, qty)
    if insert_only:
      assert price not in self._ask_price_map
    self._ask_price_map[price] = entry

    if self.bid0() is None:
      return
    ask_price = self.ask0().price
    while self.bid0() is not None and ask_price <= self.bid0().price:
      bid_price = self.bid0().price
      self._delete_bid(bid_price)
      logging.debug('REMOVE CX BID')

  def _delete_bid(self, price):
    if price in self._bid_price_map:
      del self._bid_price_map[price]
    else:
      logging.debug('DEL_BID_ERROR: %s', price)

  def _delete_ask(self, price):
    if price in self._ask_price_map:
      del self._ask_price_map[price]
    else:
      logging.debug('DEL_ASK_ERROR: %s', price)
